<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>ThreadLocal 总结 | CANCAN Love Java</title>
    <meta name="generator" content="VuePress 1.9.9">
    <link rel="icon" href="https://img.cancan.fit/vuepressBlog/avatar.jpg">
    <script language="javascript" type="text/javascript" src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script language="javascript" type="text/javascript" src="/js/MouseClickEffect.js"></script>
    <script>
          var _hmt = _hmt || [];
          (function() {
            var hm = document.createElement("script");
            hm.src = "https://hm.baidu.com/hm.js?b0aae218897fa9d8a9f76e9a77e0b3c6";
            var s = document.getElementsByTagName("script")[0]; 
            s.parentNode.insertBefore(hm, s);
          })();
        </script>
    <meta name="description" content="这里是灿灿的博客(学习版)...欢迎您的来访">
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
    
    <link rel="preload" href="/assets/css/0.styles.c492337a.css" as="style"><link rel="preload" href="/assets/js/app.15f3d1fd.js" as="script"><link rel="preload" href="/assets/js/5.ca401195.js" as="script"><link rel="preload" href="/assets/js/1.8b416e81.js" as="script"><link rel="preload" href="/assets/js/23.7fff4e5c.js" as="script"><link rel="preload" href="/assets/js/12.00b40901.js" as="script"><link rel="prefetch" href="/assets/js/10.a12826ac.js"><link rel="prefetch" href="/assets/js/11.1b7d6dd3.js"><link rel="prefetch" href="/assets/js/13.3a9b9c99.js"><link rel="prefetch" href="/assets/js/14.7d1e871c.js"><link rel="prefetch" href="/assets/js/15.e734b00e.js"><link rel="prefetch" href="/assets/js/16.6eb4ec21.js"><link rel="prefetch" href="/assets/js/17.7474baf0.js"><link rel="prefetch" href="/assets/js/18.ac8965aa.js"><link rel="prefetch" href="/assets/js/19.ebcb0e51.js"><link rel="prefetch" href="/assets/js/20.d404083b.js"><link rel="prefetch" href="/assets/js/21.6f009612.js"><link rel="prefetch" href="/assets/js/22.c65ba1bb.js"><link rel="prefetch" href="/assets/js/24.5e0f2c4a.js"><link rel="prefetch" href="/assets/js/25.f9521823.js"><link rel="prefetch" href="/assets/js/26.7ef32412.js"><link rel="prefetch" href="/assets/js/27.db55beba.js"><link rel="prefetch" href="/assets/js/28.fed9a0d9.js"><link rel="prefetch" href="/assets/js/29.71b5f381.js"><link rel="prefetch" href="/assets/js/3.ece670e3.js"><link rel="prefetch" href="/assets/js/30.353cf836.js"><link rel="prefetch" href="/assets/js/31.461dbf5d.js"><link rel="prefetch" href="/assets/js/4.cfb38e50.js"><link rel="prefetch" href="/assets/js/6.595ebcbc.js"><link rel="prefetch" href="/assets/js/7.bec14422.js"><link rel="prefetch" href="/assets/js/8.8f66a46e.js"><link rel="prefetch" href="/assets/js/9.f4c927b6.js">
    <link rel="stylesheet" href="/assets/css/0.styles.c492337a.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div class="theme-container no-sidebar" data-v-106e3130><div data-v-106e3130><LoadingPage class="loading-wrapper" data-v-106e3130 data-v-106e3130></LoadingPage> <div class="password-shadow password-wrapper-out" style="display:none;" data-v-4d3be7b7 data-v-106e3130 data-v-106e3130><h3 class="title" style="display:none;" data-v-4d3be7b7 data-v-4d3be7b7>CANCAN Love Java</h3> <!----> <label id="box" class="inputBox" style="display:none;" data-v-4d3be7b7 data-v-4d3be7b7><input type="password" value="" data-v-4d3be7b7> <span data-v-4d3be7b7>Konck! Knock!</span> <button data-v-4d3be7b7>OK</button></label> <div class="footer" style="display:none;" data-v-4d3be7b7 data-v-4d3be7b7><span data-v-4d3be7b7><i class="iconfont reco-theme" data-v-4d3be7b7></i> <a target="blank" href="https://vuepress-theme-reco.recoluan.com" data-v-4d3be7b7>vuePress-theme-reco</a></span> <span data-v-4d3be7b7><i class="iconfont reco-copyright" data-v-4d3be7b7></i> <a data-v-4d3be7b7><span data-v-4d3be7b7>灿灿爱吃肉</span>
            
          <!---->
          2023
        </a></span></div></div> <div class="hide" data-v-106e3130><div data-v-106e3130><div id="smart" class="wrapper-page" style="background-image:url(https://img.cancan.fit/vuepressBlog/bd8eb02c5773d86b315ebce8ac1000ca.jpg);background-position-x:center;background-position-y:center;background-size:cover;background-repeat-x:no-repeat;background-repeat-y:no-repeat;" data-v-106e3130><header class="navbar" data-v-106e3130><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/" class="home-link router-link-active"><img src="https://img.cancan.fit/vuepressBlog/bear.jpg" alt="CANCAN Love Java" class="logo"> <span class="site-name">CANCAN Love Java</span></a> <div class="links"><div id="dayNightSwitch" class="generalWrapper" data-v-68728e36><a class="click" data-v-68728e36><div class="onOff daySwitch" data-v-68728e36><div class="star star1" data-v-68728e36></div> <div class="star star2" data-v-68728e36></div> <div class="star star3" data-v-68728e36></div> <div class="star star4" data-v-68728e36></div> <div class="star star5" data-v-68728e36></div> <div class="star sky" data-v-68728e36></div> <div class="sunMoon" data-v-68728e36><div class="crater crater1" data-v-68728e36></div> <div class="crater crater2" data-v-68728e36></div> <div class="crater crater3" data-v-68728e36></div> <div class="cloud part1" data-v-68728e36></div> <div class="cloud part2" data-v-68728e36></div></div></div></a></div> <div class="search-box"><i class="iconfont reco-search"></i> <input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/" class="nav-link"><i class="iconfont reco-home"></i>
  主页
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-category"></i>
      博客
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/categories/日常随笔/" class="nav-link"><i class="iconfont undefined"></i>
  日常随笔
</a></li><li class="dropdown-item"><!----> <a href="/categories/灿灿爱Java/" class="nav-link"><i class="iconfont undefined"></i>
  灿灿爱Java
</a></li><li class="dropdown-item"><!----> <a href="/categories/Linux/" class="nav-link"><i class="iconfont undefined"></i>
  Linux
</a></li><li class="dropdown-item"><!----> <a href="/categories/前端技术/" class="nav-link"><i class="iconfont undefined"></i>
  前端技术
</a></li></ul></div></div><div class="nav-item"><a href="/tag/" class="nav-link"><i class="iconfont reco-tag"></i>
  标签
</a></div><div class="nav-item"><a href="/timeline/" class="nav-link"><i class="iconfont reco-date"></i>
  时间轴
</a></div><div class="nav-item"><a href="/about/" class="nav-link"><i class="iconfont reco-account"></i>
  关于
</a></div> <!----></nav></div></header> <div class="sidebar-mask" data-v-106e3130></div> <aside class="sidebar" data-v-106e3130><div class="personal-info-wrapper" data-v-d528efe2 data-v-106e3130><img src="https://img.cancan.fit/vuepressBlog/avatar.jpg" alt="author-avatar" class="personal-img" data-v-d528efe2> <h3 class="name" data-v-d528efe2>
    灿灿爱吃肉
  </h3> <div class="num" data-v-d528efe2><div data-v-d528efe2><h3 data-v-d528efe2>16</h3> <h6 data-v-d528efe2>文章</h6></div> <div data-v-d528efe2><h3 data-v-d528efe2>17</h3> <h6 data-v-d528efe2>标签</h6></div></div> <hr data-v-d528efe2></div> <nav class="nav-links"><div class="nav-item"><a href="/" class="nav-link"><i class="iconfont reco-home"></i>
  主页
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-category"></i>
      博客
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/categories/日常随笔/" class="nav-link"><i class="iconfont undefined"></i>
  日常随笔
</a></li><li class="dropdown-item"><!----> <a href="/categories/灿灿爱Java/" class="nav-link"><i class="iconfont undefined"></i>
  灿灿爱Java
</a></li><li class="dropdown-item"><!----> <a href="/categories/Linux/" class="nav-link"><i class="iconfont undefined"></i>
  Linux
</a></li><li class="dropdown-item"><!----> <a href="/categories/前端技术/" class="nav-link"><i class="iconfont undefined"></i>
  前端技术
</a></li></ul></div></div><div class="nav-item"><a href="/tag/" class="nav-link"><i class="iconfont reco-tag"></i>
  标签
</a></div><div class="nav-item"><a href="/timeline/" class="nav-link"><i class="iconfont reco-date"></i>
  时间轴
</a></div><div class="nav-item"><a href="/about/" class="nav-link"><i class="iconfont reco-account"></i>
  关于
</a></div> <!----></nav> <!----> </aside> <div class="password-shadow password-wrapper-in" style="display:none;" data-v-4d3be7b7 data-v-106e3130><h3 class="title" style="display:none;" data-v-4d3be7b7 data-v-4d3be7b7>ThreadLocal 总结</h3> <!----> <label id="box" class="inputBox" style="display:none;" data-v-4d3be7b7 data-v-4d3be7b7><input type="password" value="" data-v-4d3be7b7> <span data-v-4d3be7b7>Konck! Knock!</span> <button data-v-4d3be7b7>OK</button></label> <div class="footer" style="display:none;" data-v-4d3be7b7 data-v-4d3be7b7><span data-v-4d3be7b7><i class="iconfont reco-theme" data-v-4d3be7b7></i> <a target="blank" href="https://vuepress-theme-reco.recoluan.com" data-v-4d3be7b7>vuePress-theme-reco</a></span> <span data-v-4d3be7b7><i class="iconfont reco-copyright" data-v-4d3be7b7></i> <a data-v-4d3be7b7><span data-v-4d3be7b7>灿灿爱吃肉</span>
            
          <!---->
          2023
        </a></span></div></div></div> <div data-v-106e3130><main class="page"><div class="page-title" style="display:none;"><h1 class="title">ThreadLocal 总结</h1> <div class="page-info" data-v-04a855f8><i class="iconfont reco-account" data-v-04a855f8><span data-v-04a855f8>灿灿爱吃肉</span></i> <i class="iconfont reco-date" data-v-04a855f8><span data-v-04a855f8>2023-05-23</span></i> <i class="iconfont reco-eye" data-v-04a855f8><span id="/blogs/%E8%8B%A6%E9%80%BC%E7%A8%8B%E5%BA%8F%E5%91%98/JAVA/ThreadLocal%20%E6%80%BB%E7%BB%93.html" data-flag-title="Your Article Title" class="leancloud-visitors" data-v-04a855f8><a class="leancloud-visitors-count" style="font-size:.9rem;font-weight:normal;color:#999;"></a></span></i> <i class="iconfont reco-tag tags" data-v-04a855f8><span class="tag-item" data-v-04a855f8>java</span><span class="tag-item" data-v-04a855f8>ThreadLocal</span></i></div></div> <div class="theme-reco-content content__default" style="display:none;"><p></p><div class="table-of-contents"><ul><li><a href="#_1-底层结构">1. 底层结构</a></li><li><a href="#_2-工作原理">2. 工作原理</a></li><li><a href="#_3-使用">3. 使用</a></li><li><a href="#_4-为什么-threadlocal-threadlocalmap-底层是长度-16-的数组呢">4. 为什么 ThreadLocal.ThreadLocalMap 底层是长度 16 的数组呢？</a></li><li><a href="#_5-数据存放在数组中-那如何解决-hash-冲突问题">5. 数据存放在数组中，那如何解决 hash 冲突问题</a></li><li><a href="#_6-threadlocal-的内存泄露隐患">6. ThreadLocal 的内存泄露隐患</a></li><li><a href="#_7-为什么-threadlocalmap-的-key-是弱引用">7. 为什么 ThreadLocalMap 的 key 是弱引用</a></li><li><a href="#_8-父子线程-如何共享-threadlocal-数据">8. （父子线程）如何共享 ThreadLocal 数据</a></li></ul></div><p></p> <h2 id="_1-底层结构"><a href="#_1-底层结构" class="header-anchor">#</a> 1. 底层结构</h2> <p>ThreadLocal 底层有一个默认容量为 16 的数组组成，k 是 ThreadLocal 对象的引用，v 是要放到 TheadLocal 的值</p> <div class="language- line-numbers-mode"><pre class="language-text"><code>public void set(T value) {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
}

void createMap(Thread t, T firstValue) {
    t.threadLocals = new ThreadLocalMap(this, firstValue);
}

ThreadLocalMap(ThreadLocal&lt;?&gt; firstKey, Object firstValue) {
    table = new Entry[INITIAL_CAPACITY];
    int i = firstKey.threadLocalHashCode &amp; (INITIAL_CAPACITY - 1);
    table[i] = new Entry(firstKey, firstValue);
    size = 1;
    setThreshold(INITIAL_CAPACITY);
}

</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br></div></div><p>数组类似为 HashMap，对<font color="#FF0000">哈希冲突</font>的处理不是用链表/红黑树处理，而是使用链地址法，即尝试顺序放到哈希冲突下标的下一个下标位置。</p> <p>该数组也可以进行扩容。</p> <h2 id="_2-工作原理"><a href="#_2-工作原理" class="header-anchor">#</a> 2. 工作原理</h2> <p>一个 ThreadLocal 对象维护一个 ThreadLocalMap 内部类对象，ThreadLocalMap 对象才是存储键值的地方。</p> <p>更准确的说，是 ThreadLocalMap 的 Entry 内部类是存储键值的地方</p> <p>见源码 <font color="#FF0000">set(),createMap()</font> 可知。</p> <p><strong>因为一个 Thread 对象维护了一个 ThreadLocal.ThreadLocalMap 成员变量，且 ThreadLocal 设置值时，获取的 ThreadLocalMap 正是当前线程对象的 ThreadLocalMap。</strong></p> <div class="language- line-numbers-mode"><pre class="language-text"><code>// 获取 ThreadLocalMap 源码
ThreadLocalMap getMap(Thread t) {
    return t.threadLocals;
}
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p>所以每个线程对 ThreadLocal 的操作互不干扰，即 ThreadLocal 能实现线程隔离</p> <h2 id="_3-使用"><a href="#_3-使用" class="header-anchor">#</a> 3. 使用</h2> <div class="language- line-numbers-mode"><pre class="language-text"><code>ThreadLocal&lt;String&gt; threadLocal = new ThreadLocal&lt;&gt;();
threadLocal.set(&quot;七淅在学Java&quot;);
Integer i = threadLocal.get()
// i = 七淅在学Java

</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><h2 id="_4-为什么-threadlocal-threadlocalmap-底层是长度-16-的数组呢"><a href="#_4-为什么-threadlocal-threadlocalmap-底层是长度-16-的数组呢" class="header-anchor">#</a> 4. 为什么 ThreadLocal.ThreadLocalMap 底层是长度 16 的数组呢？</h2> <p>对 ThreadLocal 的操作见第 3 点，可以看到 ThreadLocal 每次 set 方法都是对同个 key（因为是同个 ThreadLocal 对象，所以 key 肯定都是一样的）进行操作。</p> <p>如此操作，看似对 ThreadLocal 的操作永远只会存 1 个值，那用长度为 1 的数组它不香吗？为什么还要用 16 长度呢？</p> <p>好了，其实这里有个需要注意的地方，ThreadLocal 是可以存多个值的</p> <p>那怎么存多个值呢？看如下代码：</p> <div class="language- line-numbers-mode"><pre class="language-text"><code>// 在主线程执行以下代码：
ThreadLocal&lt;String&gt; threadLocal = new ThreadLocal&lt;&gt;();
threadLocal.set(&quot;七淅在学Java&quot;);
ThreadLocal&lt;String&gt; threadLocal2 = new ThreadLocal&lt;&gt;();
threadLocal2.set(&quot;七淅在学Java2&quot;);

</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br></div></div><p>按代码执行后，看着是 new 了 2 个 ThreadLocal 对象，但实际上，数据的存储都是在同一个 ThreadLocal.ThreadLocalMap 上操作的</p> <p>再次强调：ThreadLocal.ThreadLocalMap 才是数据存取的地方，ThreadLocal 只是 api 调用入口）。真相在 ThreadLocal 类源码的 getMap()</p> <p>因此上述代码最终结果就是一个 ThreadLocalMap 存了 2 个不同 ThreadLocal 对象作为 key，对应 value 为 七淅在学Java、七淅在学Java2。</p> <p>我们再看下 ThreadLocal 的 set() 方法</p> <div class="language- line-numbers-mode"><pre class="language-text"><code>public void set(T value) {
    Thread t = Thread.currentThread();
    // 这里每次 set 之前，都会调用 getMap(t) 方法，t 是当前调用 set 方法的线程
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
}

// 重点：返回调用 set 方法的线程（例子是主线程）的 ThreadLocal 对象。  
// 所以不管 api 调用方 new 多少个 ThreadLocal 对象，它永远都是返回调用线程（例子是主线程）的 ThreadLocal.ThreadLocalMap 对象供调用线程去存取数据。
ThreadLocalMap getMap(Thread t) {
    return t.threadLocals;
}

// t.threadLocals 的声明如下
ThreadLocal.ThreadLocalMap threadLocals = null;

// 仅有一个构造方法
public ThreadLocal() {
}
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br></div></div><h2 id="_5-数据存放在数组中-那如何解决-hash-冲突问题"><a href="#_5-数据存放在数组中-那如何解决-hash-冲突问题" class="header-anchor">#</a> 5. 数据存放在数组中，那如何解决 hash 冲突问题</h2> <p>使用链地址法解决。</p> <p>具体怎么解决呢？看看执行 get、set 方法的时候：</p> <p>set：<br>
根据 ThreadLocal 对象的 hash 值，定位到 ThreadLocalMap 数组中的位置。<br>
如果位置无元素则直接放到该位置<br>
如果有元素, 且数组的 key 等于该 ThreadLocal，则覆盖该位置元素, 否则就找下一个空位置，直到找到空或者 key 相等为止。<br>
get：<br>
根据 ThreadLocal 对象的 hash 值，定位到 ThreadLocalMap 数组中的位置。<br>
如果不一致，就判断下一个位置<br>
否则则直接取出</p> <div class="language- line-numbers-mode"><pre class="language-text"><code>// 数组元素结构
Entry(ThreadLocal&lt;?&gt; k, Object v) {
    super(k);
    value = v;
}

</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br></div></div><h2 id="_6-threadlocal-的内存泄露隐患"><a href="#_6-threadlocal-的内存泄露隐患" class="header-anchor">#</a> 6. ThreadLocal 的内存泄露隐患</h2> <p>三个前置知识：</p> <ul><li>ThreadLocal 对象维护一个 ThreadLocalMap 内部类</li> <li>ThreadLocalMap 对象又维护一个 Entry 内部类，并且该类继承弱引用 WeakReference&lt;ThreadLocal&lt;?&gt;&gt;，用来存放作为 key 的 ThreadLocal 对象（可见最下方的 Entry 构造方法源码），可见最后的源码部分。</li> <li>不管当前内存空间足够与否，GC 时 JVM 会回收弱引用的内存</li></ul> <p>因为 ThreadLocal 作为弱引用被 Entry 中的 Key 变量引用，所以如果 ThreadLocal 没有外部强引用来引用它，那么 ThreadLocal 会在下次 JVM 垃圾收集时被回收。</p> <p>这个时候 Entry 中的 key 已经被回收，但 value 因为是强引用，所以不会被垃圾收集器回收。这样 ThreadLocal 的线程如果一直持续运行，value 就一直得不到回收，导致发生内存泄露。</p> <p><strong>如果想要避免内存泄漏，可以使用 ThreadLocal 对象的 remove() 方法</strong></p> <h2 id="_7-为什么-threadlocalmap-的-key-是弱引用"><a href="#_7-为什么-threadlocalmap-的-key-是弱引用" class="header-anchor">#</a> 7. 为什么 ThreadLocalMap 的 key 是弱引用</h2> <div class="language- line-numbers-mode"><pre class="language-text"><code>static class ThreadLocalMap {
    static class Entry extends WeakReference&lt;ThreadLocal&lt;?&gt;&gt; {
        /** The value associated with this ThreadLocal. */
        Object value;

        Entry(ThreadLocal&lt;?&gt; k, Object v) {
            super(k);
            value = v;
        }
    }
}

</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br></div></div><p>为什么要这样设计，这样分为两种情况来讨论：</p> <ul><li>key 使用强引用：只有创建 ThreadLocal 的线程还在运行，那么 ThreadLocalMap 的键值就都会内存泄漏，因为 ThreadLocalMap 的生命周期同创建它的 Thread 对象。</li> <li>key 使用弱引用：是一种挽救措施，起码弱引用的值可以被及时 GC，减轻内存泄漏。另外，即使没有手动删除，作为键的 ThreadLocal 也会被回收。因为 ThreadLocalMap 调用 set、get、remove 时，都会先判断之前该 value 对应的 key 是否和当前调用的 key 相等。如果不相等，说明之前的 key 已经被回收了，此时 value 也会被回收。因此 key 使用弱引用是最优的解决方案。</li></ul> <h2 id="_8-父子线程-如何共享-threadlocal-数据"><a href="#_8-父子线程-如何共享-threadlocal-数据" class="header-anchor">#</a> 8. （父子线程）如何共享 ThreadLocal 数据</h2> <ol><li>主线程创建 InheritableThreadLocal 对象时，会为 t.inheritableThreadLocals 变量创建 ThreadLocalMap，使其初始化。其中 t 是当前线程，即主线程</li> <li>创建子线程时，在 Thread 的构造方法，会检查其父线程的 inheritableThreadLocals 是否为 null。从第 1 步可知不为 null，接着 将父线程的 inheritableThreadLocals 变量值复制给这个子线程。</li> <li>InheritableThreadLocal 重写了 getMap, createMap, 使用的都是 Thread.inheritableThreadLocals 变量</li></ol> <p>如下：</p> <div class="language- line-numbers-mode"><pre class="language-text"><code>public class InheritableThreadLocal&lt;T&gt; extends ThreadLocal&lt;T&gt; 

关键源码：

第 1 步：对 InheritableThreadLocal 初始化
public class InheritableThreadLocal&lt;T&gt; extends ThreadLocal&lt;T&gt; {
    void createMap(Thread t, T firstValue) {
        t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue);
    }
}

第 2 步：创建子线程时，判断父线程的 inheritableThreadLocals 是否为空。非空进行复制
// Thread 构造方法中，一定会执行下面逻辑
if (inheritThreadLocals &amp;&amp; parent.inheritableThreadLocals != null)
    this.inheritableThreadLocals =
        ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);

第 3 步：使用对象为第 1 步创建的 inheritableThreadLocals 对象
public class InheritableThreadLocal&lt;T&gt; extends ThreadLocal&lt;T&gt; {
    ThreadLocalMap getMap(Thread t) {
       return t.inheritableThreadLocals;
    }
}

示例：
// 结果：能够输出「父线程-七淅在学Java」
ThreadLocal threadLocal = new InheritableThreadLocal();
threadLocal.set(&quot;父线程-七淅在学Java&quot;);
Thread t = new Thread(() -&gt; System.out.println(threadLocal.get()));
t.start();

// 结果：null，不能够输出「子线程-七淅在学Java」
ThreadLocal threadLocal2 = new InheritableThreadLocal();
Thread t2 = new Thread(() -&gt; {
    threadLocal2.set(&quot;子线程-七淅在学Java&quot;);
});
t2.start();
System.out.println(threadLocal2.get());

</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br><span class="line-number">28</span><br><span class="line-number">29</span><br><span class="line-number">30</span><br><span class="line-number">31</span><br><span class="line-number">32</span><br><span class="line-number">33</span><br><span class="line-number">34</span><br><span class="line-number">35</span><br><span class="line-number">36</span><br><span class="line-number">37</span><br><span class="line-number">38</span><br><span class="line-number">39</span><br></div></div></div> <footer class="page-edit" style="display:none;"><!----> <!----></footer> <!----> <!----> <!----></main> <!----></div></div></div></div></div><div class="global-ui"><div class="back-to-ceiling" style="right:1rem;bottom:6rem;width:2.5rem;height:2.5rem;border-radius:.25rem;line-height:2.5rem;display:none;" data-v-c6073ba8 data-v-c6073ba8><svg t="1574745035067" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5404" class="icon" data-v-c6073ba8><path d="M526.60727968 10.90185116a27.675 27.675 0 0 0-29.21455937 0c-131.36607665 82.28402758-218.69155461 228.01873535-218.69155402 394.07834331a462.20625001 462.20625001 0 0 0 5.36959153 69.94390903c1.00431239 6.55289093-0.34802892 13.13561351-3.76865779 18.80351572-32.63518765 54.11355614-51.75690182 118.55860487-51.7569018 187.94566865a371.06718723 371.06718723 0 0 0 11.50484808 91.98906777c6.53300375 25.50556257 41.68394495 28.14064038 52.69160883 4.22606766 17.37162448-37.73630017 42.14135425-72.50938081 72.80769204-103.21549295 2.18761121 3.04276886 4.15646224 6.24463696 6.40373557 9.22774369a1871.4375 1871.4375 0 0 0 140.04691725 5.34970492 1866.36093723 1866.36093723 0 0 0 140.04691723-5.34970492c2.24727335-2.98310674 4.21612437-6.18497483 6.3937923-9.2178004 30.66633723 30.70611158 55.4360664 65.4791928 72.80769147 103.21549355 11.00766384 23.91457269 46.15860503 21.27949489 52.69160879-4.22606768a371.15156223 371.15156223 0 0 0 11.514792-91.99901164c0-69.36717486-19.13165746-133.82216804-51.75690182-187.92578088-3.42062944-5.66790279-4.76302748-12.26056868-3.76865837-18.80351632a462.20625001 462.20625001 0 0 0 5.36959269-69.943909c-0.00994388-166.08943902-87.32547796-311.81420293-218.6915546-394.09823051zM605.93803103 357.87693858a93.93749974 93.93749974 0 1 1-187.89594924 6.1e-7 93.93749974 93.93749974 0 0 1 187.89594924-6.1e-7z" p-id="5405" data-v-c6073ba8></path><path d="M429.50777625 765.63860547C429.50777625 803.39355007 466.44236686 1000.39046097 512.00932183 1000.39046097c45.56695499 0 82.4922232-197.00623328 82.5015456-234.7518555 0-37.75494459-36.9345906-68.35043303-82.4922232-68.34111062-45.57627738-0.00932239-82.52019037 30.59548842-82.51086798 68.34111062z" p-id="5406" data-v-c6073ba8></path></svg></div><div class="Sakura" data-v-1137e66e><canvas id="canvas_sakura" style="z-index:5;" data-v-1137e66e></canvas></div><div></div><canvas id="vuepress-canvas-cursor"></canvas><APlayer audio="" fixed="true" mini="true" autoplay="autoplay" theme="#b7daff" loop="loop" order="list" preload="auto" volume="0.15" mutex="true" lrc-type="0" list-max-height="250" storage-name="vuepress-plugin-meting" id="aplayer-fixed"></APlayer><!----></div></div>
    <script src="/assets/js/app.15f3d1fd.js" defer></script><script src="/assets/js/5.ca401195.js" defer></script><script src="/assets/js/1.8b416e81.js" defer></script><script src="/assets/js/23.7fff4e5c.js" defer></script><script src="/assets/js/12.00b40901.js" defer></script>
  </body>
</html>
